<template>
  <div class="search-tree">
    <a-tree
      show-line
      show-icon
      checkable
      :checkStrictly="checkStrictly"
      :expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      :tree-data="treeData"
      :replace-fields="replaceFields"
      @select="onSelect"
      @check="treeCheck"
      @expand="onExpand"
      :selectedKeys="defaultSelectedKeys"
      v-model="mycheckedKeys"
    >
      <template slot='orgInform' slot-scope='item'>
        <span v-html="item.name.replace(new RegExp(findValue,'g'),'<span style=color:#f50>'+ findValue +'</span>')"></span>
      </template>
    </a-tree>
  </div>
</template>

<script> 
import { independentData , unitTree } from "@/api/component";
export default {
  data() {
    return {
        expandedKeys: [],
        autoExpandParent: true,
        initData:[],
        treeData:[],
        replaceFields: {
            key:'id',
            title: 'name'
        },
        findValue:'',
        selectedKeys: [],
        mycheckedKeys:{},
        checkStrictly: true,
    };
  },
  props: {
    defaultSelectedKeys:{//默认树节点蓝色选中节点 为[]时 树节点点击后 蓝色消失  不会影响下一次点击查看
      type: Array,
      default: null
    },
    searchValue:{
        type: String,
        default: ''
    },
    requestFlag:{
        type: Number,
        default: 1
    }
  },
  mounted() {
    if(this.requestFlag==1){//独立机构
      this.independentData();
    }
    if(this.requestFlag==2){//部门
      this.unitTree();
    }
  },
  methods: {
    //点击复选框触发
    treeCheck(e){
        this.mycheckedKeys.checked.splice(e.checked.length-2,e.checked.length-1);
    },
     //点击节点 查看详情
    onSelect(selectedKeys) {
      this.$emit("triggerEvent", { id: selectedKeys[0]})
    },
    //独立机构
    independentData() {
        this.loading = true;
        independentData()
        .then((res) => {
           this.setTreeData(res.data.data,'id','parentId','children');
        })
        .catch((err)=>{
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    unitTree(){ //部门
        this.loading = true;
        unitTree()
        .then((res) => {
           this.setTreeData(res.data.data,'id','parentId','children');
        })
        .catch((err)=>{
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    //处理树节点数据格式
    setTreeData(data,idFieldName,pidFieldName, childname){
        this.initData = data;
        let cloneData = JSON.parse(JSON.stringify(data))// 对源数据深度克隆
        this.treeData = cloneData.filter((father)=>{//循环所有项
            father.scopedSlots={title:'orgInform'};
            father.check = false;
            let branchArr = cloneData.filter((child)=>{
                return father[idFieldName] == child[pidFieldName]//返回每一项的子级数组
            });
            if(branchArr.length>0){
                father[childname] = branchArr;//如果存在子级，则给父级添加一个children属性，并赋值
            }
            return father[pidFieldName]==-1;//返回第一层
        });
    },
    //节点的展开收起
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //获取节点的待展开父节点
    getParentKey(id,tree){
        let parentKey,
            $this = this;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.children) {
                if (node.children.some(item => item.id === id)) {
                    parentKey = node.id;
                } else if ($this.getParentKey(id, node.children)) {
                    parentKey = $this.getParentKey(id, node.children);
                }
            }
        }
        return parentKey;
    },
    //返回勾选的树节点
    getData(){
      return this.mycheckedKeys
    }
  },
  computed: {},
  watch: {
    //父组件搜索框文字监听  标红展开相应的节点
    searchValue(n,o){
        let $this = this;
        const expandedKeys = $this.initData.map(item => {
            if (n!==''&&item.name.indexOf(n) > -1) {
                return $this.getParentKey(item.id, $this.treeData);
            }
            return null;
        }).filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign($this, {
            expandedKeys,
            findValue: n,
            autoExpandParent: true,
        });
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~stylus/mixin.styl';
.search-tree 
    overflow-y auto
    pos(115px, 24px, 24px, 24px, 1, 0)
</style>